package com.sxran.im.handler;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sxran.im.bean.AcceptGroupApplicationHttpResp;
import com.sxran.im.bean.CreateGroupReqBody;
import com.sxran.im.controller.ImController;
import com.sxran.im.dao.ImGroupMapper;
import com.sxran.im.dao.ImUserGroupMapper;
import com.sxran.im.info.ImGroup;
import com.sxran.im.info.ImGroupInvite;
import com.sxran.im.info.ImUserGroup;
import com.sxran.im.service.FriendInviteService;
import com.sxran.im.service.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CreateGroupCmdHandler extends AbstractCmdHandler<CreateGroupReqBody>{

    @Resource
    private ImGroupMapper imGroupMapper;
    @Resource
    private ImUserGroupMapper imUserGroupMapper;
    @Override
    public Object doBeanService(CreateGroupReqBody json) {
        // 1. 创建群信息。
        ImGroup group = json.getGroup();
        String groupId = group.getGroupId();
        List<String> users = json.getUsers();
        //  发送建群成功的消息。
        AcceptGroupApplicationHttpResp acceptGroupApplicationHttpResp = new AcceptGroupApplicationHttpResp();
        acceptGroupApplicationHttpResp.setSysMeg("有新人入群聊");
        acceptGroupApplicationHttpResp.setHelloMeg("欢迎加入群聊");
        acceptGroupApplicationHttpResp.setGroupId(groupId);
        acceptGroupApplicationHttpResp.setBindGroupUsers(users);
        // 如果有id就只拉人进群
        if (StrUtil.isBlank(groupId)) {
            groupId = IdUtil.getSnowflakeNextIdStr();
            group.setGroupId(groupId);
            group.setOnline(1);
            imGroupMapper.insert(group);
            // 2. 自己是管理员。
            String curUserId = ImController.getCurUserId();
            ImUserGroup userGroup = new ImUserGroup();
            userGroup.setUid(curUserId);
            userGroup.setGid(groupId);
            userGroup.setCreate_time(new Date());
            userGroup.setRole("admin");
            imUserGroupMapper.insert(userGroup);
            users.add(curUserId);
            acceptGroupApplicationHttpResp.setSysMeg("创建新的群聊");
        }
        // 3. 将人拉入群聊中。
        if (CollectionUtil.isNotEmpty(users)) {
            for (String user : users) {
                ImUserGroup userGroup = new ImUserGroup();
                userGroup.setUid(user);
                userGroup.setGid(groupId);
                userGroup.setCreate_time(new Date());
                userGroup.setRole("user");
                imUserGroupMapper.insert(userGroup);
            }
        }
        return acceptGroupApplicationHttpResp;
    }


}